/*****************************************************************************************
 **  Author:COCO 2022
 *****************************************************************************************/
//此js文件是用来自定义扩展业务代码，可以扩展一些自定义页面或者重新配置生成的代码
import { chunkArray } from '@/uitils/utils'
import { digitUppercase } from 'pixiu-number-toolkit'
import { getNowDate, formatTimeStamp } from '@/uitils/dateFormatUtil'
let extension = {
  components: {
    //查询界面扩展组件
    gridHeader: '',
    gridBody: '',
    gridFooter: '',
    //新建、编辑弹出框扩展组件
    modelHeader: '',
    modelBody: '',
    modelFooter: '',
  },
  tableAction: '', //指定某张表的权限(这里填写表名,默认不用填写)
  buttons: { view: [], box: [], detail: [] }, //扩展的按钮
  methods: {
    //下面这些方法可以保留也可以删除
    onInit() {
      //框架初始化配置前，
      //示例：在按钮的最前面添加一个按钮
      //   this.buttons.unshift({  //也可以用push或者splice方法来修改buttons数组
      //     name: '按钮', //按钮名称
      //     icon: 'el-icon-document', //按钮图标vue2版本见iview文档icon，vue3版本见element ui文档icon(注意不是element puls文档)
      //     type: 'primary', //按钮样式vue2版本见iview文档button，vue3版本见element ui文档button
      //     onClick: function () {
      //       this.$Message.success('点击了按钮');
      //     }
      //   });

      //示例：设置修改新建、编辑弹出框字段标签的长度
      // this.boxOptions.labelWidth = 150;
      //显示序号(默认隐藏)
      this.columnIndex = true
      const { permission } = this.$store.getters.getPermission(
        '/Production_PurchaseOrder'
      )
      this.editFormOptions.forEach((x) => {
        x.forEach((item) => {
          if (
            item.field == 'ReqList_Id' ||
            item.field == 'PoCode'
            // item.field == 'InvCode'
          ) {
            item.hidden = true
          }

          if (item.field == 'UnitPrice') {
            item.onKeyPress = () => {
              setTimeout(() => {
                let unitPrice = Number(this.editFormFields.UnitPrice)
                let parsePrice = parseFloat(this.editFormFields.UnitPrice)
                if (unitPrice !== unitPrice) {
                  if (this.editFormFields.UnitPrice.indexOf('NaN') !== -1) {
                    this.editFormFields.UnitPrice = ''
                  } else {
                    this.editFormFields.UnitPrice = parsePrice
                    that.$message.error('请输入数字')
                    return
                  }
                }
                let decimal = (unitPrice + '').split('.')[1]
                let integer = (unitPrice + '').split('.')[0]
                if (decimal && decimal.length > 2) {
                  this.editFormFields.UnitPrice =
                    integer + '.' + decimal.substring(0, 4)
                  return that.$message.error('最多支持2位小数')
                }
                //含税单价/税率=未税单价
                this.editFormFields.Price = (
                  unitPrice / Number(this.editFormFields.TaxRate)
                ).toFixed(4)
              }, 100)
            }
          }

          if (item.field == 'Price') {
            item.onKeyPress = () => {
              setTimeout(() => {
                let price = Number(this.editFormFields.Price)
                let parsePrice = parseFloat(this.editFormFields.Price)
                if (price !== price) {
                  if (this.editFormFields.Price.indexOf('NaN') !== -1) {
                    this.editFormFields.Price = ''
                  } else {
                    this.editFormFields.Price = parsePrice
                    that.$message.error('请输入数字')
                    return
                  }
                }
                let decimal = (price + '').split('.')[1]
                let integer = (price + '').split('.')[0]
                if (decimal && decimal.length > 4) {
                  this.editFormFields.Price =
                    integer + '.' + decimal.substring(0, 4)
                  return that.$message.error('最多支持4位小数')
                }

                //未税单价*税率=含税单价
                this.editFormFields.UnitPrice = (
                  price * Number(this.editFormFields.TaxRate)
                ).toFixed(2)
              }, 100)
            }
          }
        })
      })

      this.buttons.forEach((item) => {
        if (item.name == '新 建') {
          item.hidden = true
        }
      })

      if (permission.includes('print')) {
        this.buttons.push({
          name: '打 印',
          type: 'primary',
          icon: 'el-icon-printer',
          onClick: async () => {
            let flag = true
            let selectedList = this.$refs.table.getSelected()
            let PoList = []
            if (selectedList.length == 0)
              return this.$message.warning('请选择一条数据')
            selectedList.forEach((item) => {
              item.Status == 2 && (flag = false) 
              if (!PoList.includes(item.PoCode)) PoList.push(item.PoCode)
              for (let key in item) {
                if (item[key] == null) {
                  item[key] = ''
                }
              }
            })
            if (PoList.length > 1) {
              this.$Message.warning('选择的数据中存在多个采购单号')
              return
            }
            if(flag == false) {
              this.$Message.warning('选择的数据中存在已作废的采购单')
              return
            }

            // console.log(selectedList)
            let res = await this.http.post(
              `/api/Sys_Supplier/GetSupplier?SupplierCode=${selectedList[0].Supplier}`,
              null,
              true
            )
            // console.log(res)
            for (let key in res[0]) {
              if (res[0][key] == null) {
                res[0][key] = ''
              }
            }

            let data = {
              mainData: {
                ...res[0],
                CreateDate: getNowDate().split(' ')[0],
                PoCode: selectedList[0].PoCode,
              },
              detailData: [...selectedList],
            }

            this.print(data)
          },
        })
      }

      if (permission.includes('Cancel')) {
        this.buttons.push({
          name: '作 废',
          type: 'danger',
          icon: 'el-icon-delete',
          onClick: async () => {
            const selection = this.$refs.table.getSelected()
            if (selection.length == 0)
              return this.$message.warning('请选择一条数据')
            const idList = selection.map((item) => {
              return {
                id: item.PolList_Id,
              }
            })
            const res = await this.http.post(
              '/api/Production_PurchaseOrder/UpdateState1',
              {
                idList,
              },
              true
            )
            if (res.status) {
              this.$message.success('作废成功')
              this.search()
            } else {
              this.$message.error(res.message)
            }
          },
        })
      }

      const index = this.columns.findIndex(item => item.field == 'Qty')
      this.columns.splice(index + 1, 0, {
        field: 'WarQty',
        title: '已入库数量',
        width: 110
      })
      this.columns.forEach(item => {
        if(item.field == 'UnitPrice') {
          item.render = (h, {row}) => {
            return row.UnitPrice.toFixed(2)
          }
        }
      })
    },
    onInited() {
      //框架初始化配置后
      //如果要配置明细表,在此方法操作
      //this.detailOptions.columns.forEach(column=>{ });
    },
    searchBefore(param) {
      //界面查询前,可以给param.wheres添加查询参数
      //返回false，则不会执行查询
      return true
    },
    searchAfter(result) {
      //查询后，result返回的查询数据,可以在显示到表格前处理表格的值
      return true
    },
    addBefore(formData) {
      //新建保存前formData为对象，包括明细表，可以给给表单设置值，自己输出看formData的值
      return true
    },
    updateBefore(formData) {
      //编辑保存前formData为对象，包括明细表、删除行的Id
      return true
    },
    rowClick({ row, column, event }) {
      //查询界面点击行事件
      // this.$refs.table.$refs.table.toggleRowSelection(row); //单击行时选中当前行;
    },
    modelOpenAfter(row) {
      //点击编辑、新建按钮弹出框后，可以在此处写逻辑，如，从后台获取数据
      //(1)判断是编辑还是新建操作： this.currentAction=='Add';
      //(2)给弹出框设置默认值
      //(3)this.editFormFields.字段='xxx';
      //如果需要给下拉框设置默认值，请遍历this.editFormOptions找到字段配置对应data属性的key值
      //看不懂就把输出看：console.log(this.editFormOptions)
    },
    print(data) {
      // console.log(data)
      let printWindow = window.open('', '_blank')
      let { supplierName, CreateDate, PoCode, address, phoneNo } = data.mainData
      printWindow.document.open()
      let style = `<style>
                      .title {
                        text-align:center;
                        position: relative;
                        margin: 5px 0;
                      }

                      .header {
                        display: flex;
                        // margin-bottom: 20px;
                      }

                      .t_head {
                        flex: 1;
                        display: flex;
                        // height: 150px;
                      }

                      .t_head .th_item {
                        display: flex; 
                        list-style: none;
                        flex-direction: column;
                        flex: 1;
                      }

                      .t_head .th_item .th_title {
                        flex: 1; 
                        display: flex; 
                        justify-content: center;
                      }

                      .th_title .th_title_space {
                        display: flex; 
                        flex: 1;
                        flex-direction: column;
                        justify-content: flex-end;
                      }

                      .label {
                        display: flex;
                        align-items: flex-end;
                        text-align: left;
                      }

                      #qrcodeImg {
                        width: 100px; 
                        height: 100px;
                        margin-left: 10px;
                      }

                      .grid_table {
                        width: 100%; 
                        border: 1px solid #000; 
                        border-collapse: collapse;
                      }

                      .grid_table tr,.grid_table tr td{
                        border: 1px dotted black;
                      }

                      .grid_table tbody {
                        text-align:center;
                      }

                      .footer {
                        display: flex; 
                        justify-content: space-between; 
                        list-style: none;
                      }

                      .footer_space {
                        margin-left: 30px;
                        display: inline-block; 
                        width: 150px; 
                        border-bottom: 1px solid #000;
                      }

                      .version {
                        margin-top: 15px;
                      }

                      .cb {
                        margin-left: 20px;
                        text-align: left;
                      }
                    </style>`
      let title = `<div>
                        <h1 class="title">昆山鸿永峻精密五金电子科技有限公司</h1>
                        <h1 class="title">采购订单</h1>
                    </div>`

      let header = `<div class="header">
                        <div class="t_head">
                          <ul class="th_item">
                            <li class="th_title">
                              <span class="label"> 厂商信息: </span>
                              <span class="th_title_space" style="margin-left: 5px;">${supplierName}</span>
                            </li>
                            <li class="th_title">
                            <span class="label"> 厂商地址: </span>
                              
                              <span class="th_title_space" style="margin-left: 5px;">${address}</span>
                            </li>
                            <li class="th_title">
                            <span class="label"> 联&nbsp;&nbsp;系&nbsp;&nbsp;人: </span>
                              
                              <span class="th_title_space" style="margin-left: 5px;"></span>
                            </li>
                          </ul>

                          <ul class="th_item">
                            <li class="th_title">
                            <span class="label"> 日&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;期: </span>
                              
                              <span class="th_title_space" style="margin-left: 5px;">${CreateDate}</span>
                            </li>
                            <li class="th_title">
                            <span class="label"> 采购单号: </span>
                              
                              <span class="th_title_space" style="margin-left: 5px;">${PoCode}</span>
                            </li>
                            <li class="th_title">
                            <span class="label"> 电&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;话: </span>
                              
                              <span class="th_title_space" style="margin-left: 5px;">${phoneNo}</span>
                            </li>
                          </ul>
                        </div>
                          
                        <div id="qrcodeImg"></div>
                    </div>`
      let footer = `<div>
                    <ul class="footer"> 
                      <li>
                        核准
                        <span class="footer_space"></span>
                      </li>
                      <li>
                        审核
                        <span class="footer_space"></span>
                      </li>
                      <li>
                        采购
                        <span class="footer_space"></span>
                      </li>
                      <li>
                        <div>
                          厂商回签
                          <span class="footer_space"></span>
                        </div>
                      </li>
                    </ul>
                  <div>`
      let table = ''
      // console.log(data)
      let result = chunkArray(data.detailData, 24)
      console.log(result)
      let totalPrice = 0
      result.forEach((arr) => {
        let main = ``
        arr.forEach((item, index) => {
          totalPrice += item.Price * item.Qty
          main += `<tr>
            <td>${index + 1}</td>
            <td>${item.InvName}</td>
            <td>${item.InvCode}</td>
            <td>${item.InvStandard}</td>
            <td>${item.Unit}</td>
            <td>${item.Qty}</td>
            <td>${item.Price.toFixed(4)}</td>
            <td>${item.UnitPrice.toFixed(2)}</td>
            <td>${item.UnitPrice * item.Qty}</td>
            <td>${ formatTimeStamp(item.DeliveryDate, 'yyyy-MM-dd') }</td>
            <td></td>
          </tr>`
        })

        table += `<table class="grid_table">
          <thead>
            <tr>
              <th style="width: 50px;">序号</th>
              <th>物料名称</th>
              <th>物料编码</th>
              <th>规格</th>
              <th>单位</th>
              <th>数量</th>
              <th>未税单价</th>
              <th>含税单价</th>
              <th>含税金额</th>
              <th>交货日期</th>
              <th>备注</th>
            </tr>
          </thead>
          <tbody>
            ${main}
            <tr>
              <td colspan="2">合计</td>
              <td colspan="8" style="text-align: left;">${digitUppercase(
                totalPrice
              )}     元</td>
            </tr>
            <tr style="height: 150px;">
              <td colspan="1" rowspan="1" style="writing-mode: vertical-rl;">注意事项</td>
              <td colspan="9" style="text-align: left;">
                1、供应商须严守交货日期，若逾期交货时，需及时通知对方协商处理!否则每延迟一天，可扣该批货款3%，或将订单全部取消。<br>
                2、本公司如有指定质量标准时则依之，若本公司未指定质量标准时则依双方共同认定标准或有资格机构所认定的标准。<br>
                3、原材料内径500加内圈，单卷重量不超300KG,每栈板重量不超1000KG。<br>
                4、供应商如因交货延误、规格不符、质量不符、数量不足等造成本公司的损失，厂商应负完全责任 <br>
                5、本次定单内容或附件如有更换由采购人员通知贵厂后，原件请自行作废，不再回收。
              </td>
            </tr>
            <tr>
              <td></td>
              <td colspan="9">
                <div class="cb">
                  附件：
                  <span>
                    <input type="checkbox"> 图纸
                  </span>
                  <span>
                    <input type="checkbox"> 样品
                  </span>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
        <div>付款方式：</div>
        <div>交货地点：昆山市青阳北路565号</div>
        ${footer}`
      })

      let sscript = ` <script src="/qrcode.min.js" type="application/javascript"></script>
                      <script>
                        window.addEventListener("DOMContentLoaded", ()=> {
                          const qrcodeImgEl = document.getElementById('qrcodeImg')
                          qrcodeImgEl.innerHTML = ''
                          let qrcode = new QRCode(qrcodeImgEl, {
                                                  width: 100,
                                                  height: 100,
                                                  colorDark: '#000000',
                                                  colorLight: '#ffffff',
                                                  correctLevel: QRCode.CorrectLevel.H,
                                        })
                          qrcode.makeCode('${PoCode}')
                        })
                      </script>`
      printWindow.document.write(
        `<html><head><title>Print</title>${style}</head><body>`
      )
      printWindow.document.write(title)
      printWindow.document.write(header)
      printWindow.document.write(table)
      // printWindow.document.write(footer)
      printWindow.document.write(`</body>${sscript}</html>`)
      printWindow.document.close()
      setTimeout(() => {
        printWindow.print()
        printWindow.close()
      }, 100)
    },
  },
}
export default extension
